package org.daochong.fastdev.funcs;

import java.sql.SQLException;

import org.daochong.fastdev.Context;
import org.daochong.fastdev.Function;
import org.daochong.lang.JsonAccessException;
import org.daochong.lang.StringUtils;

public class ExceptionFunction implements Function {

	@Override
	public boolean is(String id) {
		return "exception".equals(id) || id.startsWith("exception.");
	}

	@Override
	public void exec(String key, String prop, Context context) throws SQLException {
		if (!is(key) || StringUtils.isEmpty(prop) || context == null) {
			return;
		}
		if (key.startsWith("exception.")) {
			try {
				int code = Integer.parseInt(key.substring(10));
				throw new JsonAccessException(code, prop);
			} catch (RuntimeException e) {
				throw e;
			} catch (Throwable e) {
				throw new JsonAccessException(10000, "Process Fail", e);
			}
		} else {
			Object o = context.expression(prop);
			if (o instanceof Throwable) {
				if (o instanceof RuntimeException) {
					throw (RuntimeException) o;
				} else {
					throw new JsonAccessException(10000, (Throwable) o);
				}
			} else {
				throw new JsonAccessException(10000, "Unkown Exception");
			}
		}
	}

}
